package com.apes.framework.util;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * 功能：日期相关工具类
 *
 * @author xul
 * @create 2017-12-02 16:08
 */
public class DateUtil {
    public static final String SHOW_DATE_FORMAT = "yyyy-MM-dd";
    public static final String SHOW_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String SHOW_DATETIME_MILLI_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
    public static final String SHOW_DATETIME_UTC_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
    public static final String ShOW_DATETIME_GMT_FORMAT = "EEE MMM ddHH:mm:ss 'GMT' yyyy";
    public static final String SHOW_TIME_FORMAT = "HH:mm";
    public static final String SHOW_MONTH_FORMAT = "yyyy-MM";
    public static final String SHOW_DATE_NUMBER_FORMAT = "yyyyMMdd";

    /**
     * @param str String 时间格式字串
     * @return String 带“-”分隔符的格式化时间字串
     */
    public static String strToDateStr(String str) throws Exception {
        String strDes = "", strTime = "";
        if (str.indexOf("/") > -1) {
            str = str.replaceAll("/", "-");
        }
        if (str.indexOf(".") > -1) {
            str = str.replaceAll("\\.", "-");
        }
        if (str.indexOf("-") == -1) {

            for (int i = 0; i <= str.length() - 1; i++) {
                if (((i % 4 == 0) || (i % 6 == 0)) && (i != 0) && (i <= 6)) {
                    strDes += "-";
                }
                if (i == 8) {
                    strDes += " ";
                } else {
                    strDes += str.charAt(i);
                }
            }

            if (strDes.length() > 19) {
                System.out.println(strDes.substring(0, 19));
                strTime += strDes.substring(0, 19);
                strDes = "";
                strDes += strTime;
            }
            return strDes;
        } else
            return str;
    }

    /***
     * 功能: 将Date 转化为指定类型
     */
    public static java.util.Date dateToDate(Date date, String pattern){
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            return sdf.parse(sdf.format(date));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 功能：字符串转成Date
     */
    public static java.util.Date parse(String source) {
        return parse(source, SHOW_DATE_FORMAT);
    }

    /**
     * 功能：字符串转成Date
     */
    public static java.util.Date parse(String source, String pattern) {
        Calendar calendar = Calendar.getInstance();
        try {
            source = strToDateStr(source);
            calendar.setTime(new SimpleDateFormat(pattern).parse(source));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new java.util.Date(calendar.getTimeInMillis());
    }

    /**
     * 功能：字符串转成Date
     */
    public static java.util.Date parseUTC(String source) {
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(new SimpleDateFormat(SHOW_DATETIME_UTC_FORMAT).parse(source));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new java.util.Date(calendar.getTimeInMillis());
    }

    /**
     * 功能：格式化当前日期
     */
    public static Date getDate(String format) {
        Date now = new Date();
        if (format.trim().length() != 0) {
            now = DateUtil.parse(DateUtil.format(now, format.trim()), format.trim());
        }
        return now;
    }

    public static Timestamp parseTimestamp(String source) {
        Calendar calendar = Calendar.getInstance();
        try {
            SimpleDateFormat sdf;
            if (source.contains("Z")) {
                sdf = new SimpleDateFormat(SHOW_DATETIME_UTC_FORMAT);
                sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
            } else if (source.contains("GMT")) {
                sdf = new SimpleDateFormat(ShOW_DATETIME_GMT_FORMAT);
            } else {
                sdf = new SimpleDateFormat(SHOW_DATETIME_FORMAT);
            }
            Date date = sdf.parse(source);
            calendar.setTime(date);
        } catch (Exception e) {
            calendar.setTimeInMillis(Long.valueOf(source));
        }
        return new Timestamp(calendar.getTimeInMillis());
    }

    public static Timestamp getTimestamp() {
        return parseTimestamp(format());
    }

    /**
     * 功能：指定时间戳转为字符
     */
    public static String timeStampToStr(Long timeStamp) {
        return format(new Date(timeStamp), SHOW_DATETIME_MILLI_FORMAT);
    }

    /**
     * 功能：当前时间转为字符
     */
    public static String format() {
        return format(SHOW_DATETIME_MILLI_FORMAT);
    }

    /**
     * 功能：当前时间转为字符
     */
    public static String format(String pattern) {
        return format(new Date(), pattern);
    }

    /**
     * 功能：指定时间转为字符
     */
    public static String format(Date date, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }

    /**
     * 功能：日期增加天、月、年.....
     */
    public static Date add(Date date, int field, int amt) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(field, amt);
        return calendar.getTime();
    }

    /**
     * 比较日期（年月日）
     */
    public static int dateCompare(Date date1, Date date2) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(SHOW_DATE_FORMAT);
        Date dateFirst;
        try {
            dateFirst = dateFormat.parse(dateFormat.format(date1));
            Date dateLast = dateFormat.parse(dateFormat.format(date2));
            if (dateFirst.after(dateLast)) {
                return 1;
            } else if (dateFirst.before(dateLast)) {
                return -1;
            }
            return 0;
        } catch (ParseException e) {
            return 2;
        }
    }

    /**
     *   java.util.Date --> java.time.LocalDate
     */
    public static LocalDate UDateToLocalDate(Date date) {
        Instant instant = date.toInstant();
        ZoneId zone = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
        return localDateTime.toLocalDate();
    }

    /**
     *    java.time.LocalDate --> java.util.Date
     */
    public static Date ULocalDateToDate(LocalDate localDate) {
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = localDate.atStartOfDay().atZone(zone).toInstant();
        Date date = Date.from(instant);
        return date;
    }

    /**
     * 获取当天最大时间
     *
     * @return 时间戳
     */
    public static Date getEndTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        return calendar.getTime();
    }

    /***
     * 获取月最大值
     */
    public static Date getMonthLastDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.set(Calendar.DAY_OF_MONTH, lastDay);
        return calendar.getTime();
    }

    /***
     * 获取月最小值
     */
    public static Date getMonthFirstDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int firstDay = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
        calendar.set(Calendar.DAY_OF_MONTH, firstDay);
        return calendar.getTime();
    }

    /***
     * 获取日期所在年的第一天
     */
    public static Date getYearFirstDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int firstDay = calendar.getActualMinimum(Calendar.DAY_OF_YEAR);
        calendar.set(Calendar.DAY_OF_YEAR, firstDay);
        return calendar.getTime();
    }

    /**
     * 获取自定义时间
     * @param month:月,以当前月为基准
     * @param day:日
     * @param hour:时
     * @param minute:分
     * @param second:秒
     * @return
     */
    public static Date getCustomDate(int month, int day, int hour, int minute, int second){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, month);
        calendar.set(Calendar.DAY_OF_MONTH, day);
        calendar.set(Calendar.HOUR_OF_DAY,hour);
        calendar.set(Calendar.MINUTE,minute);
        calendar.set(Calendar.SECOND,second);
        Date startDate = calendar.getTime();
        return startDate;
    }

    /**
     * 判断时间是否在时间段内
     * @param nowTime
     * @param beginTime
     * @param endTime
     * @return
     */
    public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
        if (nowTime.getTime() == beginTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        Date startDate = null;
        Date executeDate1 = DateUtil.getCustomDate(0, 1, 0, 0, 0);
        if (DateUtil.dateCompare(new Date(),executeDate1) == 0){
            //当前时间为1号则执行的数据是上个月15-最后一天，所以开始日期为15号
            startDate = DateUtil.getCustomDate(0, 15, 0, 0, 0);
        }else {
            //16号执行的是1-15号数据，所以开始日期为1号
            startDate = DateUtil.getCustomDate(0, 1, 0, 0, 0);
            DateUtil.add(startDate, Calendar.DAY_OF_MONTH, -1);
        }
        System.out.println(DateUtil.add(startDate, Calendar.DAY_OF_MONTH, -1));

        LocalDate localDate = DateUtil.UDateToLocalDate(new Date(startDate.getTime()));
        System.out.println(localDate.getDayOfMonth());

    }
}

